clear
* Change directory to where the folder with the data is
cd "Data Archive TWT Predictions\KTHDP"

use DatasetKTHDP.dta,clear
*Merge estimated risk attitudes
merge m:1 subj using UtilityEstimationCARAKTHDP, nogen
*keep only useful variables and collapse dataset at the subject and choice pair level
collapse prob1 prob2 out1 out2 choiceleft  est_r_u*  noise_u* idleft idright, by(subj idpair)

*variales necessary for normalization
egen m1 = max(out1)
egen m2 = max(out2)
gen maxOut=max(m1,m2)

tab choiceleft, missing
replace choiceleft=1 if choiceleft>0.5
replace choiceleft=0 if choiceleft<0.5
********************************

*Calculate EU and correctly predicted choices out-of-sample
local i = 1
while `i' < 6 {
preserve
gen rhat = est_r_u`i'
gen EUA= prob1*((1-exp(-est_r_u *out1)) /(1-exp(-est_r_u *(maxOut))))  
gen EUB= prob2*((1-exp(-est_r_u *out2)) /(1-exp(-est_r_u *(maxOut))))  
gen diffeu  = EUA  - EUB  

*Calculate prediction EU
gen predchoiceeu = 1 if diffeu>0  & idleft!=`i' & idright!=`i'
replace predchoiceeu =0 if diffeu<0  & idleft!=`i' & idright!=`i'
tab predchoiceeu, missing

*Calculate correctly predicted choices
gen corrpredeuCARA =0    if predchoice != choiceleft    & choiceleft!=. & predchoiceeu !=.
replace corrpredeuCARA=1 if predchoice == choiceleft   & choiceleft!=. & predchoiceeu !=.
gen corrpredeuCARA`i' =corrpredeuCARA
tab corrpredeuCARA, missing
****************************************
collapse corrpredeuCARA`i', by(subj)
sum corrpredeuCARA`i', detail
save corrpredeuCARA`i', replace
restore
local i = `i' + 1
}

*Merge all datasets
use corrpredeuCARA1, replace
merge 1:1 subj using corrpredeuCARA2, nogen
merge 1:1 subj using corrpredeuCARA3, nogen
merge 1:1 subj using corrpredeuCARA4, nogen
merge 1:1 subj using corrpredeuCARA5, nogen
sum corrpredeuCARA*
save PredEUCARAKTHDP, replace

*Repeat the same procedure for RUM-CRRA, RPM-CARA, and RPM-CRRA.
*saved files should be:
* PredEUCRRAKTHDP
* PredEURPMCRRAKTHDP
* PredEURPMCRRAKTHDP
